package reflection;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//通过反射，动态创建对象
public class Test09 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        //1.获得 class对象
        Class c1 = Class.forName("reflection.User");

        //2.构造对象

        //显示无参
        /*User user = (User) c1.getDeclaredConstructor().newInstance();
        System.out.println(user);

        //有参
        User user2 = (User) c1.getDeclaredConstructor(String.class,int.class,int.class).newInstance("zsh",1,1);
        System.out.println(user2);*/

        //通过反射调用普通方法
        User u3 = (User) c1.getDeclaredConstructor().newInstance();
        //获得方法
        Method setName = c1.getMethod("setName", String.class);

        //invoke 激活方法，（对象，方法的值）
        setName.invoke(u3,"zsh");
        System.out.println(u3.getName());

        //访问私有属性
        System.out.println("===========================");
        User u4 = (User) c1.getDeclaredConstructor().newInstance();
        Field name = c1.getDeclaredField("name");

        name.setAccessible(true); //关闭安全检查，可以操作私有属性
        name.set(u4,"zsh2");
        System.out.println(u4.getName());

    }
}
